import {
	Controller,
	Get,
	Post,
	Body,
	Patch,
	Param,
	Delete,
	Query,
	HttpException,
	HttpStatus,
} from "@nestjs/common";
import { UserService } from "./user.service";
import { CreateUserDto } from "./dto/create-user.dto";
import { UpdateUserDto } from "./dto/update-user.dto";
import * as bcrypt from "bcrypt";

@Controller("users")
export class UserController {
	constructor(private readonly userService: UserService) {}

	@Post("create")
	async create(@Body() createUserDto: CreateUserDto) {
		const user = await this.userService.create(createUserDto);
		return {
			code: 200,
			data: user,
			message: "用户创建成功",
		};
	}

	@Get("list")
	async findAll(@Query() query) {
		const [users, total] = await this.userService.findAll(query);
		return {
			code: 200,
			data: {
				list: users,
				total,
				page: +query.page || 1,
				limit: +query.limit || 10,
			},
			message: "获取用户列表成功",
		};
	}

	@Get("findOne/:id")
	async findOne(@Param("id") id: string) {
		const user = await this.userService.findOne(+id);
		return {
			code: 200,
			data: user,
			message: "获取用户详情成功",
		};
	}

	@Patch("update/:id")
	async update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {
		const user = await this.userService.update(+id, updateUserDto);
		return {
			code: 200,
			data: user,
			message: "用户更新成功",
		};
	}

	@Delete("delete/:id")
	async remove(@Param("id") id: string) {
		await this.userService.remove(+id);
		return {
			code: 200,
			message: "用户删除成功",
		};
	}

	@Patch("reset-password/:id")
	async resetPassword(
		@Param("id") id: string,
		@Body() body: { password: string }
	) {
		try {
			const user = await this.userService.findOne(+id);
			console.log("原始密码:", body.password);

			// 直接更新密码，加密过程在service层处理
			await this.userService.update(+id, { password: body.password });

			return {
				code: 200,
				message: "密码重置成功",
			};
		} catch (error) {
			if (error instanceof HttpException) {
				throw error;
			}
			throw new HttpException("密码重置失败", HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
}
